package com.example.multidatasource.config;


import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.LocalCacheScope;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

public class AbstractMybatisConfig {

    protected HikariDataSource getDataSource(String dataSourceName) {
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setPoolName(dataSourceName);
        return dataSource;
    }

    protected SqlSessionFactoryBean getSqlSessionFactory(DataSource dataSource, MybatisProperties properties, String mapperLocation, LocalCacheScope localCacheScope) throws Exception {
        final SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setTypeHandlersPackage(properties.getTypeHandlerPackage());

        Configuration configuration = new Configuration();
        configuration.setMapUnderscoreToCamelCase(true);

        // 禁用以及缓存
        if (localCacheScope != null) {
            configuration.setLocalCacheScope(localCacheScope);
        }

        sqlSessionFactoryBean.setConfiguration(configuration);

        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResource(mapperLocation));
        return sqlSessionFactoryBean;
    }

}
